package com.yisu.expressway.shopping_mall;

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.R;
import com.yisu.expressway.fragment.BaseFragment;
import com.yisu.expressway.model.ProductItem;
import com.yisu.expressway.model.ShopCategory;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.ui.recyclerview.BaseRvAdapter;
import com.yisu.expressway.ui.recyclerview.DividerListItemDecoration;
import com.yisu.expressway.ui.recyclerview.PagingRecyclerView;
import com.yisu.expressway.ui.refresh.SuperSwipeRefreshLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2016/10/8 0008.
 */

public class ShopCategoryFragment extends BaseFragment implements PagingRecyclerView.SampleActionListener {

    @Bind(R.id.rv_content)
    protected PagingRecyclerView mRv_goodsList;
    @Bind(R.id.refreshLayout)
    protected SuperSwipeRefreshLayout swipeRefreshLayout;

    public static final String TAG_CONTENT = "tag_content";

    private View parentView;
    private ShopCategory mCategoryTag;
    private ImageView carImage;
    private AnimationDrawable mAnimation;
    private boolean isFreshEnable;

    public ShopCategoryFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (parentView == null) {
            parentView = inflater.inflate(R.layout.recycler_view_with_swiperefresh, container, false);
            ButterKnife.bind(this,parentView);
            mCategoryTag = (ShopCategory) getArguments().get(TAG_CONTENT);
            if(mCategoryTag != null){
                initFreshLayout();
                DividerListItemDecoration mListDivider = new DividerListItemDecoration(getActivity(), LinearLayoutManager.VERTICAL);
                mRv_goodsList.init(mListDivider,new LinearLayoutManager(getActivity()),this,40);
            }

        }

        ViewGroup rootView = (ViewGroup) parentView.getParent();
        if (rootView != null) {
            rootView.removeView(parentView);
        }


        return parentView;
    }

    private void initFreshLayout(){
        swipeRefreshLayout.setHeaderViewBackgroundColor(0xffefeff4);
        swipeRefreshLayout.setHeaderView(createHeaderView());
        swipeRefreshLayout.setTargetScrollWithLayout(true);
        swipeRefreshLayout
                .setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

                    @Override
                    public void onRefresh() {
                        mAnimation.start();
                        mRv_goodsList.refreshData();
                    }

                    @Override
                    public void onPullDistance(int distance) {
                        int index = distance / 25;

                        int resId = R.drawable.car_1;
                        switch (index){
                            case 2:
                                resId = R.drawable.car_2;
                                break;
                            case 3:
                                resId = R.drawable.car_3;
                                break;
                            case 4:
                                resId = R.drawable.car_4;
                                break;
                            case 5:
                                resId = R.drawable.car_5;
                                break;
                            case 6:
                                resId = R.drawable.car_6;
                                break;
                            case 7:
                                resId = R.drawable.car_7;
                                break;
                            case 8 :
                                resId = R.drawable.car_8;
                                break;
                            case 9:
                                resId = R.drawable.car_9;
                                break;
                            case 10 :
                                resId = R.drawable.car_10;
                                break;
                        }

                        if(!isFreshEnable) {
                            carImage.setBackgroundResource(resId);
                        }
                    }

                    @Override
                    public void onPullEnable(boolean enable) {
                        // textView.setText(enable ? "松开刷新" : "下拉刷新");
                        isFreshEnable = enable;
                        if(enable) {
                            carImage.setBackgroundResource(R.color.colorTransparent);
                            carImage.setImageResource(R.drawable.car_frame);
                            mAnimation = (AnimationDrawable) carImage.getDrawable();
                        }
                    }
                });

    }

    private View createHeaderView() {
        View headerView = LayoutInflater.from(swipeRefreshLayout.getContext())
                .inflate(R.layout.layout_head, null);
        carImage = (ImageView) headerView.findViewById(R.id.pb_view);
        return headerView;
    }

    @Override
    public void fetchData(int start, int pageSize) {
        getGoodsList();
    }

    @Override
    public BaseRvAdapter.SampleViewHolder createItemViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.shopping_item_list,null);
        return new GoodsViewHolder(itemView);
    }

    @Override
    public void bindData(BaseRvAdapter.SampleViewHolder _holder, int position, Object _item) {
        final GoodsViewHolder holder = (GoodsViewHolder)_holder;
        final ProductItem item = (ProductItem)_item;
        Glide.with(getActivity().getApplicationContext())
                .load(item.imageUrl)
                .asBitmap()
                .placeholder(R.drawable.blank)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .animate(R.anim.fade_in_image)
                .into(holder.mIv_cover);
        holder.mTv_desc.setText(item.productName);
        holder.mTv_price.setText(getString(R.string.money_sign) + item.productPrice);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                YouZanWebActivity.launch(getActivity(),item.linkUrl,"");
            }
        });


    }


    class GoodsViewHolder extends BaseRvAdapter.SampleViewHolder {

        @Bind(R.id.iv_cover) ImageView mIv_cover;
        @Bind(R.id.tv_des) TextView mTv_desc;
        @Bind(R.id.tv_price) TextView mTv_price;

        public GoodsViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        ButterKnife.unbind(this);
    }

    private void getGoodsList(){

        Map<String, Object> params = new HashMap();
        params.put("categoryId", mCategoryTag.id);
        ApiClientHelper.postApi(ApiSetting.getGoodsList(), new TypeToken<ArrayList<ProductItem>>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<ArrayList<ProductItem>>>() {
            @Override
            public void onResponse(ApiResult<ArrayList<ProductItem>> result) {
                if (!result.success) {
                    mRv_goodsList.dataFetchFail(result.getMsg());
                    return;
                }

                mRv_goodsList.dataFetchDone(result.getResult());
                if(mAnimation != null) {
                    swipeRefreshLayout.setRefreshing(false);
                    mAnimation.stop();
                    carImage.setImageResource(R.color.colorTransparent);
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mRv_goodsList.dataFetchFail(volleyError.getMessage());
            }
        }, this);
    }
}
